package ws.rest.check.manager;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ws.rs.core.MultivaluedMap;

import org.dom4j.DocumentException;

import ws.rest.check.base.BaseResourceImpl;
import ws.rest.check.base.Check;
import ws.rest.check.exception.CheckConditionLogicException;
import ws.rest.check.exception.CheckResourceNotValidException;
import ws.rest.check.exception.ValidatorNotSupportedException;
import ws.rest.check.validator.CheckItem;
import ws.rest.check.validator.CheckResult;
import ws.rest.check.validator.DataChecker;

public class CheckManager {
	private static DataChecker checker = new DataChecker() ;
    private static CheckManager instance = new CheckManager();
    private static String ENCODING  = "UTF-8";

    static {
    };

    private CheckManager() {
    }
    
    public static CheckManager getInstance() {
        return instance;
    }
    
	public Map<Object, Object> pretreatRequestData(
			MultivaluedMap<String, String> formData) throws UnsupportedEncodingException {
		Map<Object,Object> result = new HashMap<Object,Object>();
		Map<String,Object> iter = new HashMap<String,Object>();

		for(String it:formData.keySet()){
			String key = URLDecoder.decode(it, ENCODING);
			if(key.length()==0)
				continue;
			String value = URLDecoder.decode(formData.getFirst(key), ENCODING);
			if(key.contains("-")){
				String splice[] = key.trim().split("-");
				int count,index;
				if(splice.length == 2){
					String keyName = splice[0],keyIndex = splice[1];
					if(result.get(keyName)==null){
						Map<String,Object> loopTempValues = new HashMap<String,Object>();
						loopTempValues.put("count",0);
						loopTempValues.put("data", new HashMap<Integer,Object>());
						result.put(keyName, loopTempValues);
					}
					Map<String,Object> ref = (Map<String, Object>) result.get(keyName);
					count = (Integer)ref.get("count");
					index = Integer.parseInt(keyIndex);
					ref.put("count", count+1);
					((Map<Integer, Object>) ref.get("data")).put(index, value);
				}
			}else{
				result.put(key, value);
			}
		}
		// 整理数组
		for (Object key : result.keySet()) {
			Object value = result.get(key);

			if (value instanceof Map<?, ?>) {
				Integer count = (Integer) ((Map<?, ?>) value).get("count");
				Map<Integer, Object> data = (Map<Integer, Object>) ((Map<?, ?>) value).get("data");
				//按照key排序
				if (null != count) {
					Object[] values = new Object[count.intValue()];
					Object[]   keyArr   =  data.keySet().toArray();   
					Arrays.sort(keyArr); 
					int idx=0;
					for (Object k : keyArr) {
						values[idx] = data.get(k);  
						idx++;
					}
					result.put(key, values);
				} else {
					result.put(key, null);
				}
			}
		}
		
		return result;
	}
	
	public CheckResult checkRequestData(Map<Object, Object> requestData, String id){
		List<CheckItem> itemList = BaseResourceImpl.getInstance().getCheckResource(requestData,id);
		try {
			CheckResult result = this.checker.checkData(requestData, itemList, null);
			if (false == result.isPassed()) {
				System.out.println("校验失败：\n" + result);
			}
			return result;
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (ValidatorNotSupportedException e) {
			e.printStackTrace();
		} catch (CheckResourceNotValidException e) {
			e.printStackTrace();
		} catch (CheckConditionLogicException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public CheckResult checkRequestData(Map<Object, Object> requestData, List<CheckItem> items,
			Check customeChecker){
		try {
			
			CheckResult result = this.checker.checkData(requestData, items, customeChecker);

			if (false == result.isPassed()) {
				System.out.println("校验失败：\n" + result);
			}

			return result;
		} catch (DocumentException e) {
			e.printStackTrace();
			System.out.println("校验：解析check.xml失败");
		} catch (CheckConditionLogicException e) {
			e.printStackTrace();
			System.out.println("校验：条件结构语法错误");
		} catch (ValidatorNotSupportedException e) {
			e.printStackTrace();
			System.out.println("校验：校验方法不存在");
		} catch (CheckResourceNotValidException e) {
			e.printStackTrace();
			System.out.println("校验：解析check.xml出错");
		}
		return null;
	}

}